import com.bullsora.kindlerss.fulfillment.FulfillmentService
import com.bullsora.kindlerss.model.AppUser
import com.bullsora.kindlerss.model.AppUserRole
import com.bullsora.kindlerss.model.Role
import grails.util.Environment
import org.apache.log4j.Logger

class BootStrap {

  private static def LOG = Logger.getLogger(this)
  
  FulfillmentService fulfillmentService

  def grailsApplication
  
  def init = { servletContext ->
    LOG.info("-------- Beginning bootstrap")
//    LOG.info("Current config : ${grailsApplication.config.flatten()}")
    def userRole = createRole('ROLE_USER')
    def adminRole = createRole('ROLE_ADMIN')
    def facebookRole = createRole('ROLE_FACEBOOK')

    if (Environment.current == Environment.DEVELOPMENT) {
      if (!AppUser.findByUsername('test')) {
        def testUser = new AppUser(username: "test",
                                   password: "test",
                                   enabled: true,
                                   passwordExpired: false,
                                   kindleAccount: "bullsora",
                                   timeZone: "GMT+3").save(flush: true)
        new AppUserRole(role: userRole, appUser: testUser).save(flush: true)
      }
    }

    String adminUsername = grailsApplication.config.app.admin.username
    if (adminUsername && !AppUser.findByUsername(adminUsername)) {
      LOG.info("------------- Creating administrator user ${adminUsername}")
      def adminUser = new AppUser(username: adminUsername,
                                  password: grailsApplication.config.app.admin.password,
                                  enabled: true,
                                  passwordExpired: false).save(flush: true)
      new AppUserRole(role: adminRole, appUser: adminUser).save(flush: true)
    }

    fulfillmentService.init()
    LOG.info("--------------- Ending bootstrap")
  }

  private def createRole(String role) {
    def userRole = Role.findByAuthority(role)
    if (!userRole) {
      userRole = new Role(authority: role).save(failOnError: true, flush: true)
    }
    return userRole
  }

  def destroy = {
    fulfillmentService.destroy()
  }
}
